package top.hkyzf.study.leetcode.hash;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 朱峰
 * @date 2022-1-26 8:34
 */
public class 检测正方形_2013 {
    public static void main(String[] args) {
        DetectSquares obj = new DetectSquares();
        int[] point1 = {5,10};
        int[] point2 = {10,5};
        int[] point3 = {10,10};
        int[] point4 = {5,5};
        int[] point5 = {3,0};
        int[] point6 = {8,0};
        int[] point7 = {8,5};
        int[] point8 = {3,5};
        int[] point9 = {9,0};
        int[] point10 = {9,8};
        int[] point11 = {1,8};
        int[] point12 = {1,0};
        int[] point13 = {0,0};
        int[] point14 = {8,0};
        int[] point15 = {8,8};
        int[] point16 = {0,8};

        obj.add(point1);
        obj.add(point2);
        obj.add(point3);
        System.out.println(obj.count(point4));
        obj.add(point5);
        obj.add(point6);
        obj.add(point7);
        System.out.println(obj.count(point8));
        obj.add(point9);
        obj.add(point10);
        obj.add(point11);
        System.out.println(obj.count(point12));
        obj.add(point13);
        obj.add(point14);
        obj.add(point15);
        System.out.println(obj.count(point16));
    }
}

class DetectSquares {
    private final Map<Integer, Map<Integer, Integer>> points = new HashMap<>();

    public DetectSquares() {
    }

    public void add(int[] point) {
        Map<Integer, Integer> pt = points.getOrDefault(point[0], new HashMap<>());
        pt.put(point[1], pt.getOrDefault(point[1], 0) + 1);
        points.put(point[0], pt);
    }

    public int count(int[] point) {
        int x = point[0];
        int y = point[1];
        int result = 0;
        if (!points.containsKey(x)) {
            return 0;
        }
        Map<Integer, Integer> yMap = points.get(x);
        Set<Integer> ySet = yMap.keySet();
        for (int yKey : ySet) {
            // x=point[0]=1, y=point[1]=3, x=1, y=yKey=1 ...
            if (yKey == y) {
                continue;
            }
            Set<Integer> xSet = points.keySet();
            // x=xKey, y=yKey
            for (int xKey : xSet) {
                if (xKey == x) {
                    continue;
                }
                if (points.get(xKey).containsKey(yKey) && points.get(xKey).containsKey(y)) {
                    if(Math.abs(xKey-x) == Math.abs(yKey-y)) {
                        result += points.get(x).get(yKey) * points.get(xKey).get(yKey) * points.get(xKey).get(y);
                    }
                }
            }
        }
        return result;
    }
}
